package com.ahu.xrq.demo.service.impl;

import com.ahu.xrq.demo.dao.AreaDao;
import com.ahu.xrq.demo.entity.Area;
import com.ahu.xrq.demo.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class AreaServiceImpl implements AreaService{
	@Autowired
	private AreaDao areaDao;
	@Override
	public List<Area> getAreaList() {
		return areaDao.queryArea();
	}

	@Override
	public Area getAreaById(int areaId) {
		return areaDao.queryAreaById(areaId);
	}

	@Transactional  //Transactional 默认是接受RuntimeException进行logback回滚
	@Override
	public boolean addArea(Area area) {
		if (area.getAreaName()!=null&&"".equals(area.getAreaName())){
			area.setCreateTime(new Date());
			area.setLastEditTime(new Date());
			try{
				int effctedNum = areaDao.insertArea(area);
				if (effctedNum>0){
					return true;
				}else {
					throw new RuntimeException("插入区域信息失败!");
				}
			}catch (Exception e){
				throw new RuntimeException("插入区域信息失败："+e.getMessage());
			}
		}else {
			throw new RuntimeException("区域信息不能为空");
		}
	}

	@Override
	public boolean modifyArea(Area area) {
		//空值判断，主要是areaId不能为空
		if (area.getAreaId()!=null&&"".equals(area.getAreaName())){
			//设置默认值
			area.setLastEditTime(new Date());
			try{
				//更新区域信息
				int effctedNum = areaDao.updateArea(area);
				if (effctedNum>0){
					return true;
				}else {
					throw new RuntimeException("更新区域信息失败!");
				}
			}catch (Exception e){
				throw new RuntimeException("更新区域信息失败："+e.getMessage());
			}
		}else {
			throw new RuntimeException("区域信息不能为空");
		}
	}

	@Override
	public boolean deleteArea(int areaId) {
		if (areaId>0){
			try{
				int effctedNum = areaDao.deleteArea(areaId);
				if (effctedNum>0){
					return true;
				}else {
					throw new RuntimeException("删除区域信息失败!");
				}
			}catch (Exception e){
				throw new RuntimeException("删除区域信息失败!"+e.toString());
			}
		}else {
			throw new RuntimeException("区域Id信息不能为空");
		}
	}
}
